const { User } = require('../models')
const { failure } = require('../utils/responses');
const { UnauthorizedError } = require('../utils/errors')
const jwt = require('jsonwebtoken');

module.exports = async (req, res, next) => {
    try {
        //判断token是否存在
        const { token } = req.headers;
        if (!token) {
            throw new UnauthorizedError('当前接口需要验证才能登陆');
        }

        //验证token是否正确
        const decoded = jwt.verify(token, process.env.SECRET);

        //从jwt中解析之前存入的userId
        const { userId } = decoded;

        //如果通过验证，将userId挂在到req上，方便后续中间件或路由使用
        req.userId = userId;
        next();
    } catch (error) {
        failure(res, error);
    }
}

